package cn.dceast.former.controller;

import cn.dceast.common.data.RtnData;
import cn.dceast.common.utils.StringUtil;
import cn.dceast.former.model.EyeModelData;
import cn.dceast.former.model.EyeModelField;
import cn.dceast.former.model.EyeModelUploadCloum;
import cn.dceast.former.service.EyeModelCommentService;
import cn.dceast.former.service.EyeModelService;
import cn.dceast.former.service.EyeUploadInfoService;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by fanbo on 2017-07-18.
 * 模型信息
 */
@Controller
@RequestMapping("/eyeModelController")
@Api(tags = {"eyeModelController"})
public class EyeModelController {
    public static final Logger logger = LoggerFactory.getLogger(EyeModelController.class);
    @Autowired
    private EyeModelService eyeModelService;
    @Autowired
    private EyeUploadInfoService eyeUploadInfoService;

    /**
     * 模型列表（我的模型，系统模型）
     * @param userId 用户ID
     * @param industryId 行业id
     * @param sceneId 场景Id
     * @param modelName 模型名称
     * @param modelType 模型类型
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "模型列表", notes = "模型列表")
    @RequestMapping(value = "/getModelList.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getModelList (@RequestParam(required = false) String loginId,
                                 @RequestParam(required = false) String userId,
                                 @RequestParam(required = false) String industryId,
                                 @RequestParam(required = false) String sceneId,
                                 @RequestParam(required = false) String modelName,
                                 @RequestParam(required = false) String modelType,
                                 @RequestParam(required = false) String modelState,
                                 @RequestParam(value = "pageIndex",defaultValue = "0" , required = false) int pageIndex,
                                 @RequestParam(value = "pageSize",defaultValue = "10", required = false) int pageSize
                                 ,HttpServletRequest request){
        HttpSession session = request.getSession();
        String userid_session=null;
        if (session != null) {
            userid_session = session.getAttribute("userid")!=null?session.getAttribute("userid").toString():"";
        }
        //参数集合
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            if(pageIndex == 0){
                params.put("startIndex",pageIndex);
            }else {
                params.put("startIndex", (pageIndex - 1) * pageSize);
            }
            params.put("pageSize",pageSize);
            if(userId!=null && userId.equals("admin")) {
                //公共模型
                params.put("userId", "");
                params.put("loginId", StringUtil.isEmpty(loginId) ? userid_session : loginId);
                params.put("modelState","10002");
            }else{
                params.put("loginId", StringUtil.isEmpty(loginId) ? userid_session : loginId);
                params.put("userId", StringUtil.isEmpty(userId) ? userid_session : userId);
                params.put("modelState",modelState);
            }
            params.put("industryId",industryId);
            params.put("sceneId",sceneId);
            params.put("modelName",modelName);
            params.put("modelType",modelType);

            //查询数据
            List<Map<String,Object>> returnList = eyeModelService.getModelList(params);
            Integer listCountNum = eyeModelService.getModelListCount(params);
            //返回值放入集合
            Map<String,Object> retMap = new HashMap<String, Object>();
            retMap.put("list",returnList);
            retMap.put("count",listCountNum);
            return RtnData.ok(retMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("========查询模型列表失败=========",e);
        }
        return RtnData.fail("","查询模型列表失败");
    }


    @ApiOperation(value = "根据数据模型ID，查询模型详情数据", notes = "根据数据模型ID，查询模型详情数据")
    @RequestMapping(value = "/getModelDataById.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getModelDataById(@RequestParam(required = true) int modelId,HttpServletRequest request){
        HttpSession session = request.getSession();
        String userid=null;
        if (session != null) {
            userid = session.getAttribute("userid")!=null?session.getAttribute("userid").toString():"1";
        }
        Map<String,Object> retMap = new HashMap<String, Object>();
        try {
            retMap.put("modelData",eyeModelService.getModelDataById(modelId));
            retMap.put("evaluateData",eyeModelService.getModelEvalUateById(modelId,Integer.parseInt(userid)));
            return RtnData.ok(retMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("========查询模型详情信息失败=========",e);
        }
        return RtnData.fail("查询模型详情信息失败");
    }

    /**
     * 模型的基本信息添加
     * @param modelIdOld 当该值为空的时候，代表是数据的新增，当该有值的时候，代表是编辑
     * @param modelName 模型名称
     * @param userId 创建者
     * @param industryId 行业ID
     * @param sceneId 场景ID
     * @param picUrlName 模型的缩略图地址
     * @param modelDesc 模型的描述
     * @param request
     * @return
     */
    @ApiOperation(value = "模型的基本信息添加", notes = "模型的基本信息添加")
    @RequestMapping(value = "/addModelBasicInfo.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData addModelBasicInfo(@RequestParam(required = true) String modelIdOld,
                                     @RequestParam(required = true) String modelName,
                                     @RequestParam(required = true) String userId,
                                     @RequestParam(required = true) String industryId,
                                     @RequestParam(required = true) String sceneId,
                                     @RequestParam(required = true) String picUrlName,
                                     @RequestParam(required = true) String modelDesc,
                                     HttpServletRequest request){
        HttpSession session = request.getSession();
        String uid=null;
        if (session != null) {
            uid = session.getAttribute("userid")!=null?session.getAttribute("userid").toString():userId;
        }
        //将参数汇总在集合
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("modelName",modelName);
        paramMap.put("userId",uid);

        paramMap.put("industryId",industryId);
        paramMap.put("sceneId",sceneId);
        paramMap.put("picUrlName",picUrlName);
        paramMap.put("modelDesc",modelDesc);
        paramMap.put("modelIdOld",modelIdOld);
        //编辑功能
        if(StringUtil.isNotEmpty(modelIdOld)){
            //查询模型名称是否已经存在()
            List<Map<String,Object>> modelListByIdName = eyeModelService.getModelByIdAndName(paramMap);
            if(modelListByIdName!=null && modelListByIdName.size()>0){
                logger.info("模型名称没有修改，不需要验证名称是否重复");
            }else{
                List<Map<String,Object>> modelList = eyeModelService.getModelByName(paramMap);
                if(modelList!=null && modelList.size()>0){
                    return RtnData.fail("","模型名称已经存在，请修改模型名称!");
                }
            }
            try {
                EyeModelData emd = new EyeModelData();
                emd.setModelName(modelName);
                emd.setModelDesc(modelDesc);
                emd.setCreateTime(new Date());
                emd.setCreator(uid);
                emd.setId(Integer.parseInt(modelIdOld));
                emd.setModelState("10004");
                emd.setModelPic(picUrlName);
                //保存模型基本信息(暂存)
                eyeModelService.editModelBasicInfo(emd);
                //删除关系表（行业和场景与模型之间的关系）
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("modelId", modelIdOld);
                eyeModelService.deleteContactByModelId(deleteMap);
                //重新存入关系表
                this.saveContact(industryId, sceneId, Integer.parseInt(modelIdOld));
                return RtnData.ok(Integer.parseInt(modelIdOld), "请求成功");
            }catch (Exception ex){
                ex.printStackTrace();
                return RtnData.fail("","请求失败");
            }
        }
        //新增功能
        try{
            //查询模型名称是否已经存在()
            List<Map<String,Object>> modelList = eyeModelService.getModelByName(paramMap);
            if(modelList!=null && modelList.size()>0){
               return RtnData.fail("","模型名称已经存在，请修改模型名称!");
            }

            EyeModelData emd = new EyeModelData();
            emd.setModelName(modelName);
            emd.setModelDesc(modelDesc);
            emd.setCreateTime(new Date());
            emd.setCreator(uid);
            emd.setModelState("10004");
            emd.setModelPic(picUrlName);
            //保存模型基本信息(暂存)
            eyeModelService.addModelBasicInfo(emd);
            int modelId =emd.getId();
            this.saveContact(industryId,sceneId,modelId);
            return RtnData.ok(modelId,"请求成功");

        }catch (Exception ex){
            ex.printStackTrace();
           return RtnData.fail("","请求失败");
        }

    }

    /**
     * 保存行业和场景到关系表中
     * @param industryId
     * @param sceneId
     * @param modelId
     */
    public void saveContact(String industryId,String sceneId,int modelId){
        //保存行业和场景到关系表中
        Object[] induObj = null;
        if(StringUtil.isNotEmpty(industryId)){
            induObj = industryId.split(";");
            for(Object obj:induObj){
                Map<String,Object> map = new HashMap<>();
                map.put("modelId",modelId);
                map.put("industry",obj);
                eyeModelService.addModelContact(map);
            }
        }
        Object[] sceneObj = null;
        if(StringUtil.isNotEmpty(sceneId)) {
            sceneObj = sceneId.split(";");
            for (Object obj : sceneObj) {
                Map<String, Object> map = new HashMap<>();
                map.put("modelId", modelId);
                map.put("scene", obj);
                eyeModelService.addModelContactScene(map);
            }
        }
    }


    @ApiOperation(value = "查询模型数据项具体描述", notes = "查询模型数据项具体描述")
    @RequestMapping(value = "/getModelFieldDataById.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getModelFieldDataById (@RequestParam(required = true) String modelId){
        List<EyeModelField> midList =  eyeModelService.getModelFieldDataById(modelId);
        if(midList!=null && midList.size()>0){
            return RtnData.ok(midList);
        }else{
            return RtnData.fail("没有数据项描述");
        }
    }

    @ApiOperation(value = "查询上传的元数据字段信息，并且计算出最大值与最小值",
            notes = "查询上传的元数据字段信息，并且计算出最大值与最小值")
    @RequestMapping(value = "/getUploadDataList.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getUploadDataList(@RequestParam(required = true) String modelId){

        if(StringUtil.isEmpty(modelId)){
            return RtnData.fail("","模型ID为空");
        }
        List<Map<String,Object>> rtnList = eyeUploadInfoService.getUploadDataList(Integer.parseInt(modelId));
        if(rtnList!=null && rtnList.size()>0){
            Map<String,Object> map = new HashMap<>();
            map.put("list",rtnList);
            return RtnData.ok(map);
        }
        return RtnData.fail("","没有相关字段信息");
    }

    @ApiOperation(value = "根据模型ID得到上传数据源的列信息",
            notes = "根据模型ID得到上传数据源的列信息")
    @RequestMapping(value = "/getUploadDataListByUseModel.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getUploadDataListByUseModel(@RequestParam(required = true) String modelId){

        if(StringUtil.isEmpty(modelId)){
            return RtnData.fail("","模型ID为空");
        }
        List<Map<String,Object>> rtnList = eyeUploadInfoService.getUploadDataListByUseModel(Integer.parseInt(modelId));
        if(rtnList!=null && rtnList.size()>0){
            Map<String,Object> map = new HashMap<>();
            map.put("list",rtnList);
            return RtnData.ok(map);
        }
        return RtnData.fail("","没有相关字段信息");
    }

    /**
     * 更新模型状态
     * @param modelId
     * @param stateId
     * @return
     */
    @ApiOperation(value = " 更新模型状态",
            notes = " 更新模型状态")
    @RequestMapping(value = "/updateModelState.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData updateModelState(@RequestParam(required = true) String modelId,
                                    @RequestParam(required = true) String stateId){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("modelId",modelId);
        paramMap.put("stateId",stateId);
        try {
            eyeModelService.updateModelState(paramMap);
        }catch (Exception ex){
            ex.printStackTrace();
            return RtnData.fail("","更新失败");
        }
        return RtnData.ok("保存成功")
                ;
    }


    /**
     * 模型删除功能
     * @param modelId

     * @return
     */
    @ApiOperation(value = " 模型删除功能",
            notes = " 模型删除功能")
    @RequestMapping(value = "/deleteModelById.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData deleteModelById(@RequestParam(required = true) String modelId){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("modelId",modelId);

        try {
            eyeModelService.deleteModelById(paramMap);
        }catch (Exception ex){
            ex.printStackTrace();
            return RtnData.fail("","删除失败");
        }
        return RtnData.ok("删除成功");
    }

    @ApiOperation(value = "根据模型ID查询数据字段名", notes = "根据模型ID查询数据字段名")
    @RequestMapping(value = "/getModelFieldById.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getModelFieldById(@RequestParam(required = true) int modelId){

        //查询模型字段列表
        List<Map<String,Object>> fieldList = eyeModelService.getModelTableById(modelId);

        Map<String,Object> rtnMap = new HashMap<>();

        rtnMap.put("dataList",fieldList);

        return RtnData.ok(rtnMap);

    }

    /**
     * 模型字段   // 数据元字段
     *
     * @param eye_model_id
     * @param Inviolate
     * @return
     */
    @ApiOperation(value = "添加数据源接口", notes = "添加数据源接口")
    @RequestMapping(value = "/insertDataByModelid.do", method = RequestMethod.POST)
    @ResponseBody
    public RtnData insertDataByModelid(@RequestParam String eye_model_id, @RequestParam String[] Inviolate, HttpServletRequest request){
        HttpSession session = request.getSession();
        String userid=null;
        if (session != null) {
            userid = session.getAttribute("userid")!=null?session.getAttribute("userid").toString():"1";
        }
        if(StringUtil.isEmpty(eye_model_id)){
            return RtnData.fail("","参数错误，请稍后重试");
        }

        for (String s : Inviolate) {
            String[] field = null;
            field = s.split("=");//等号分割
            if(field.length==3){

                String cloumnName=field[1];
                String valName=field[0];
                String tableName=field[2];

                EyeModelUploadCloum emuc = new EyeModelUploadCloum();
                emuc.setTablename(tableName);

                emuc.setCloumname(cloumnName != null ? cloumnName.toString() : "");
                emuc.setModelid(Integer.parseInt(eye_model_id));
                emuc.setValname(valName != null ? valName.toString() : "");
                emuc.setOnlyvalue("--");
                emuc.setSkewvalue("--");
                emuc.setStandvalue("--");
                //判断该字段所有的值是否是数值型
                Map<String,Object> paramMap = new HashMap<>();
                paramMap.put("tableName",tableName);
                paramMap.put("dataCname",cloumnName);
                List<Map<String,Object>> dataNumList = eyeUploadInfoService.checkDataIsNum(paramMap);
                if(dataNumList!=null && dataNumList.size()>0){
                    Map<String,Object> rtnMap = dataNumList.get(0);
                    Integer numCount = rtnMap.get("nums")!=null?Integer.parseInt(rtnMap.get("nums").toString()):0;
                    if(numCount>0){
                        emuc.setMaxvalueEd("---");
                        emuc.setMinvalueEd("---");
                        emuc.setAveragevalue("---");
                    }else {
                        emuc.setMaxvalueEd(rtnMap.get("maxVal") != null ? rtnMap.get("maxVal").toString() : "--");
                        emuc.setMinvalueEd(rtnMap.get("minVal") != null ? rtnMap.get("minVal").toString() : "--");
                        emuc.setAveragevalue(rtnMap.get("averVal") != null ? rtnMap.get("averVal").toString() : "--");
                    }
                    emuc.setValidvalue(rtnMap.get("validValue")!=null?rtnMap.get("validValue").toString():"--");
                }else{
                    emuc.setMaxvalueEd("--");
                    emuc.setMinvalueEd("--");
                    emuc.setAveragevalue("--");
                    emuc.setValidvalue("--");
                }
                eyeUploadInfoService.updateUploadInfo(emuc);

            }
        }
        return RtnData.ok("");

    }
}
